package com.lcgroup.springdemo.demos.interceptor;

import com.alibaba.fastjson.JSON;
import com.lcgroup.springdemo.demos.handler.GlobeExceptionHandler;
import com.lcgroup.springdemo.demos.bean.ResultResponse;
import com.lcgroup.springdemo.demos.bean.ZSException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
@Slf4j
public class GlobeInterceptor implements HandlerInterceptor {

    @Resource
    private GlobeExceptionHandler globeExceptionHandler;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入拦截器preHandle");
        String interceptor = request.getHeader("interceptor");
        if ("1".equals(interceptor)){
            return true;
        }else {
//            response.flushBuffer();
//            ResultResponse<String> stringResultResponse = globeExceptionHandler.handleException(new ZSException("拦截器报错"));
            throw new ZSException("拦截器报错");
//            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
//            response.setCharacterEncoding("UTF-8");
//            response.getWriter().write(JSON.toJSONString(stringResultResponse));
//            response.getWriter().flush();
//            response.getWriter().close();
        }
//        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("进入拦截器postHandle");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("进入拦截器afterCompletion");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
